//
//  GQHTrucksController.m
//  Xanthium
//
//  Created by GuanQinghao on 07/03/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#pragma mark Macro
#import "GQHHeader.h"

#pragma mark Model
#import "GQHTruckModel.h"

#pragma mark Object

#pragma mark View
#import "GQHTrucksView.h"

#pragma mark Controller
#import "GQHTrucksController.h"
#import "GQHRoutesController.h"
#import "GQHTruckInfoController.h"
#import "GQHRegionController.h"
#import "GQHLengthController.h"
#import "GQHModelController.h"

#pragma mark CocoaPods

#pragma mark ----------Header End----------

@interface GQHTrucksController () <GQHTrucksViewDelegate> {
    
#pragma mark Data
    /// 请求参数
    NSMutableDictionary *parameters;
    /// 返回模型数组
    __block NSMutableArray<GQHTruckModel *> *truckModelArray;
    
    __block int _page;
#pragma mark View
    /// 自定义根视图
    GQHTrucksView *rootView;
}

@end


@implementation GQHTrucksController

#pragma mark --Lifecycle
- (void)loadView {
    DLog();
    
    rootView = [[GQHTrucksView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    rootView.qh_delegate = self;
    self.view = rootView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    DLog();
    
    parameters = [NSMutableDictionary dictionary];
    [parameters setObject:USER_GET_ID forKey:@"token"];
    [parameters setObject:ROWS forKey:@"rows"];
    
    rootView.qh_tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [parameters setObject:@"" forKey:@"origin"];
        [parameters setObject:@"" forKey:@"source"];
        [parameters setObject:@"" forKey:@"demandModels"];
        [parameters setObject:@"" forKey:@"keyWord"];
        rootView.textField.text = @"";
        [parameters setObject:[NSNumber numberWithInt:_page] forKey:@"page"];
        
        [self pullRefresh:parameters];
    }];
    [rootView.qh_tableView.mj_header beginRefreshing];
    [self fetchServiceDataWithParameters:parameters];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    DLog();
    
    self.qh_leftButton.hidden = YES;
    self.qh_titleLabel.text = @"找车";
    [self.qh_rightButton setTitle:@"路线" forState:UIControlStateNormal];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [rootView.qh_tableView.mj_header beginRefreshing];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    DLog();
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [rootView.qh_tableView.mj_header endRefreshing];
}

#pragma mark --Delegate

- (void)searchKeyWord:(NSString *)keyWord
{
    [parameters setObject:keyWord forKey:@"keyWord"];
    [self fetchServiceDataWithParameters:parameters];
}

// 点击列表项
- (void)qh_selectedRowWithTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
    
    GQHTruckModel *truckModel = truckModelArray[indexPath.row];
    
    GQHTruckInfoController *truckInfoController = [[GQHTruckInfoController alloc] init];
    truckInfoController.qh_truckID = truckModel.qh_truckID;
    truckInfoController.qh_freeTruck = @"YES";
    truckInfoController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:truckInfoController animated:YES];
}

// 点击选择起始地
- (void)qh_checkDeparture:(UIButton *)sender {
    
    __block UIButton *button = sender;
    
    GQHRegionController *regionController = [[GQHRegionController alloc] init];
    regionController.qh_regionBlock = ^(NSString *regionID, NSString *regionName, CLLocation *location)
     {
        DLog(@"%@--%@",regionID, regionName);
        
        if (regionID) {
            
            [button setTitle:regionName forState:UIControlStateNormal];
            [parameters setObject:regionID forKey:@"originId"];
            [self fetchServiceDataWithParameters:parameters];
        } else {
            
            [button setTitle:@"起始地" forState:UIControlStateNormal];
            [parameters setObject:@"" forKey:@"originId"];
            [self fetchServiceDataWithParameters:parameters];
        }
    };
    regionController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:regionController animated:YES];
}

// 点击选择目的地
- (void)qh_checkDestination:(UIButton *)sender {
    
    __block UIButton *button = sender;
    
    GQHRegionController *regionController = [[GQHRegionController alloc] init];
    regionController.qh_regionBlock = ^(NSString *regionID, NSString *regionName, CLLocation *location)
    {
        DLog(@"%@--%@",regionID, regionName);
        
        if (regionID) {
            
//            [button setTitle:regionName forState:UIControlStateNormal];
            [parameters setObject:regionID forKey:@"destinationId"];
            [self fetchServiceDataWithParameters:parameters];
        } else {
            
//            [button setTitle:@"目的地" forState:UIControlStateNormal];
            [parameters setObject:@"" forKey:@"destinationId"];
            [self fetchServiceDataWithParameters:parameters];
        }
    };
    regionController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:regionController animated:YES];
}

// 点击选择来源类型
- (void)qh_checkType:(UIButton *)sender {
    
    __block UIButton *button = sender;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"全部" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
//        [button setTitle:@"全部" forState:UIControlStateNormal];
        [parameters setObject:@"" forKey:@"source"];
        [self fetchServiceDataWithParameters:parameters];
        [rootView.qh_tableView.mj_header beginRefreshing];
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"我关注的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [button setTitle:@"我关注的" forState:UIControlStateNormal];
        [parameters setObject:@"我关注的" forKey:@"source"];
        [self fetchServiceDataWithParameters:parameters];
        [rootView.qh_tableView.mj_header beginRefreshing];
    }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

// 点击选择更多
- (void)qh_checkMore:(UIButton *)sender {
    
    __block UIButton *button = sender;
    
    /// 需求车型
    GQHModelController *modelController = [[GQHModelController alloc] init];
    modelController.qh_modelBlock = ^(NSString *modelID, NSString *modelName) {
        
        if (modelID) {
            
//            [button setTitle:modelName forState:UIControlStateNormal];
            [parameters setObject:modelID forKey:@"vehicleclassificationcode"];
            [self fetchServiceDataWithParameters:parameters];
        } else {
            
//            [button setTitle:@"更多" forState:UIControlStateNormal];
            [parameters setObject:@"" forKey:@"vehicleclassificationcode"];
            [self fetchServiceDataWithParameters:parameters];
        }
    };
    
    modelController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:modelController animated:YES];
}

- (void)qh_dialMobile:(UIButton *)sender {
    
    [self qh_checkAccessPermissionType:GQHAccessPermissionTypeJunior allowed:^{
        DLog(@"拨打电话");
        
        GQHTruckModel *truckModel = truckModelArray[sender.tag];
        [self qh_dialWithMobile:truckModel.qh_driverMobile];
    } unallowed:nil];
}

#pragma mark --TargetMethod
-(void)qh_clickedRightButton:(UIButton *)sender {
    
    [self qh_checkAccessPermissionType:GQHAccessPermissionTypeJunior allowed:^{
        DLog(@"路线");
        
        GQHRoutesController *routesController = [[GQHRoutesController alloc] init];
        routesController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:routesController animated:YES];
    } unallowed:nil];
}

#pragma mark --PrivateMethod
- (void)fetchServiceDataWithParameters:(NSMutableDictionary *)parameters {
    
    [self pullRefresh:parameters];
    
    rootView.qh_tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        _page++;
        [parameters setObject:[NSNumber numberWithInt:_page] forKey:@"page"];
        
        [GQHTruckModel qh_fetchFreeTrucksWithParameters:parameters success:^(BOOL status, NSNumber *code, NSString *message, NSArray<GQHTruckModel *> *trucks) {
            
            if (status) {
                
                if (trucks && trucks.count > 0) {
                    
                    [truckModelArray addObjectsFromArray:trucks];
                    rootView.qh_truckModelArray = truckModelArray;
                    [rootView.qh_tableView reloadData];
                    [rootView.qh_tableView.mj_footer endRefreshing];
                } else {
                    
                    [rootView.qh_tableView.mj_footer endRefreshingWithNoMoreData];
                }
            } else {
                
                [self showToastWithText:message];
                [rootView.qh_tableView.mj_footer endRefreshing];
            }
        } failure:^(NSError *error) {
            
            NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
            [self showToastWithText:errorString];
            [rootView.qh_tableView.mj_footer endRefreshing];
        }];
    }];
}

- (void)pullRefresh:(NSMutableDictionary *)parameters
{
    [GQHTruckModel qh_fetchFreeTrucksWithParameters:parameters success:^(BOOL status, NSNumber *code, NSString *message, NSArray<GQHTruckModel *> *trucks)
    {
        if (status) {
            
            truckModelArray = [NSMutableArray arrayWithArray:trucks];
            rootView.qh_truckModelArray = truckModelArray;
            [rootView.qh_tableView reloadData];
        } else {
            
            [self showToastWithText:message];
        }
        [rootView.qh_tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        
        NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
        [self showToastWithText:errorString];
        [rootView.qh_tableView.mj_header endRefreshing];
    }];
}

#pragma mark --Setter

#pragma mark --Getter

#pragma mark --View

@end
